/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package bd.org.apache.commons.math.random;

import bd.org.apache.commons.math.exception.NotStrictlyPositiveException;
import bd.org.apache.commons.math.util.FastMath;

/**
 * Base class for random number generators that generates bits streams.
 *
 * @version $Id: BitsStreamGenerator.java 1244107 2012-02-14 16:17:55Z erans $
 * @since 2.0
 */
public abstract class BitsStreamGenerator implements RandomGenerator {

    /**
     * Next gaussian.
     */
    private double nextGaussian;

    /**
     * Creates a new random number generator.
     */
    public BitsStreamGenerator() {

        nextGaussian = Double.NaN;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public abstract void setSeed(int seed);

    /**
     * {@inheritDoc}
     */
    @Override
    public abstract void setSeed(int[] seed);

    /**
     * {@inheritDoc}
     */
    @Override
    public abstract void setSeed(long seed);

    /**
     * Generate next pseudorandom number.
     * <p>This method is the core generation algorithm. It is used by all the
     * public generation methods for the various primitive types {@link
     * #nextBoolean()}, {@link #nextBytes(byte[])}, {@link #nextDouble()},
     * {@link #nextFloat()}, {@link #nextGaussian()}, {@link #nextInt()},
     * {@link #next(int)} and {@link #nextLong()}.</p>
     *
     * @param bits number of random bits to produce
     * @return random bits generated
     */
    protected abstract int next(int bits);

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean nextBoolean() {

        return next(1) != 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void nextBytes(byte[] bytes) {

        int i = 0;
        final int iEnd = bytes.length - 3;
        while (i < iEnd) {
            final int random = next(32);
            bytes[i] = (byte) (random & 0xff);
            bytes[i + 1] = (byte) ((random >> 8) & 0xff);
            bytes[i + 2] = (byte) ((random >> 16) & 0xff);
            bytes[i + 3] = (byte) ((random >> 24) & 0xff);
            i += 4;
        }
        int random = next(32);
        while (i < bytes.length) {
            bytes[i++] = (byte) (random & 0xff);
            random = random >> 8;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double nextDouble() {

        final long high = ((long) next(26)) << 26;
        final int low = next(26);
        return (high | low) * 0x1.0p-52d;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public float nextFloat() {

        return next(23) * 0x1.0p-23f;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double nextGaussian() {

        final double random;
        if (Double.isNaN(nextGaussian)) {
            // generate a new pair of gaussian numbers
            final double x = nextDouble();
            final double y = nextDouble();
            final double alpha = 2 * FastMath.PI * x;
            final double r = FastMath.sqrt(-2 * FastMath.log(y));
            random = r * FastMath.cos(alpha);
            nextGaussian = r * FastMath.sin(alpha);
        } else {
            // use the second element of the pair already generated
            random = nextGaussian;
            nextGaussian = Double.NaN;
        }

        return random;

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int nextInt() {

        return next(32);
    }

    /**
     * {@inheritDoc}
     * <p>This default implementation is copied from Apache Harmony
     * java.util.Random (r929253).</p>
     * <p>Implementation notes: <ul>
     * <li>If n is a power of 2, this method returns
     * {@code (int) ((n * (long) next(31)) >> 31)}.</li>
     * <li>If n is not a power of 2, what is returned is {@code next(31) % n}
     * with {@code next(31)} values rejected (i.e. regenerated) until a
     * value that is larger than the remainder of {@code Integer.MAX_VALUE / n}
     * is generated. Rejection of this initial segment is necessary to ensure
     * a uniform distribution.</li></ul></p>
     */
    @Override
    public int nextInt(int n) throws IllegalArgumentException {

        if (n > 0) {
            if ((n & -n) == n) {
                return (int) ((n * (long) next(31)) >> 31);
            }
            int bits;
            int val;
            do {
                bits = next(31);
                val = bits % n;
            } while (bits - val + (n - 1) < 0);
            return val;
        }
        throw new NotStrictlyPositiveException(n);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public long nextLong() {

        final long high = ((long) next(32)) << 32;
        final long low = ((long) next(32)) & 0xffffffffL;
        return high | low;
    }

    /**
     * Clears the cache used by the default implementation of
     * {@link #nextGaussian}.
     */
    public void clear() {

        nextGaussian = Double.NaN;
    }

}
